package genstream.file

import genstream._
import java.io.{FileOutputStream, FileInputStream, File}
import scaladuct.{Starter, Extensible}
import javax.validation.constraints.NotNull

/**
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: 12.4.11
 * Time: 12:29
 * To change this template use File | Settings | File Templates.
 */

class FileResource(val file: File, metadata: Extensible) extends InputResource with OutputResource {

  def this(cookie: FileResourceStarterCookie) = this(new File(cookie.filePath), null)

  def openIterator(context: StreamingContext) = new ListStreamIterator(
    List(new DefaultInputStreamHolder(new FileInputStream(file), metadata)))

  def openFragmentedOutputStream(context: StreamingContext) = new DefaultFragmentedOutputStream(
    new FileOutputStream(file), metadata)
}

@serializable
@SerialVersionUID(1L)
class FileResourceStarterCookie {
  @NotNull
  var filePath: String = null
}

@SerialVersionUID(1L)
class FileResourceStarter extends Starter[ServiceFactory[FileResource]] {

  def newInstance(): ServiceFactory[FileResource] = phaseFile(new FileResourceStarterCookie)

  def phaseFile(cookie: FileResourceStarterCookie): ServiceFactory[FileResource] = {
    new FunctionalServiceFactory(new FileResource(cookie))
  }

  def destroy(instance: ServiceFactory[FileResource]) = null

}

